package org.hry.netty.filter;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @Desc
 * @Author houry
 * @Date 2021/2/20 15:43
 **/
public class IpFilterNettyServerHandler extends SimpleChannelInboundHandler<String> {


    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("[MyServerHandler]-[channelRegistered]-[被调用]");
    }


    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("[MyServerHandler]-[channelUnregistered]-[被调用]");

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("[MyServerHandler]-[channelActive]-[被调用]");
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("[MyServerHandler]-[channelInactive]-[被调用]");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("[MyServerHandler]-[channelRead0]-[被调用]-[接收到信息：" + msg + "]");
    }


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("[MyServerHandler]-[channelReadComplete]-[被调用]");
        ctx.channel().config().setWriteBufferHighWaterMark(1);

    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        if (ctx.channel().isWritable()){
            System.out.println("[MyServerHandler]-[channelWritabilityChanged]-[被调用]");
        }

//        super.channelWritabilityChanged(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("[MyServerHandler]-[channelRead]-[被调用]-[接收到信息：" + msg + "]");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("[MyServerHandler]-[exceptionCaught]-[被调用]");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("[MyServerHandler]-[userEventTriggered]-[被调用]");
        System.out.println("~~~~~~~~~~~~~~~userEventTriggered~~~~~~~~~~~~~");
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                throw new Exception("idle exception");
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
